package cn.historia.trigger.listener;

import cn.historia.domain.strategy.service.IRaffleStock;
import cn.historia.types.event.BaseEvent;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @package: cn.historia.trigger.listener
 * @className: StrategyAwardStockZeroCustomer
 * @author: 云溪
 * @description:
 * @date: 2025/9/29 10:55
 * @version: 1.0
 */

@Slf4j
@Component
public class StrategyAwardStockZeroCustomer {

    @Value("${spring.rabbitmq.topic.strategy_award_stock_zero}")
    private String topic;

    @Resource
    private IRaffleStock raffleStock;


    @RabbitListener(queuesToDeclare = @Queue(value = "strategy_award_stock_zero"))
    public void listener(String message){
        try {
            log.info("监听抽奖奖品库存消耗为0消息 topic: {} message: {}", topic, message);
            // 转换对象
            BaseEvent.EventMessage<Map<String, Object>> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<Map<String, Object>>>(){}.getType());
            Map<String, Object> data = eventMessage.getData();
            Long strategyId = ((Integer) data.get("strategyId")).longValue();
            Integer awardId = (Integer) data.get("awardId");
            log.info("监听抽奖奖品库存消耗为0消息，开始处理 strategyId: {} awardId: {}", strategyId, awardId);
            // 更新库存
            raffleStock.clearStrategyAwardStock(strategyId, awardId);
            // // 清空队列
            // raffleStock.clearQueueValue();
        } catch (Exception e) {
            log.error("监听抽奖奖品库存消耗为0消息，消费失败 topic: {} message: {}", topic, message);
            throw e;
        }

    }


}
